<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchIntercityNotInvoicedOrderListAPI } from '@/apis/fetchIntercityNotInvoicedOrderList'
import type { IntercityTripData, LoadMoreData, NormalTripData } from '@/types/api'
import { useUserInfoStore } from '@/store/userInfo'
import { fetchNotInvoicedOrderListAPI } from '@/apis/fetchNotInvoicedOrderList'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const type = ref<'normal' | 'intercity'>()

onLoad((options) => {
  if (!options?.type) {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    return
  }
  type.value = options.type
})

const selectedTrips = ref<(NormalTripData | IntercityTripData)[]>([])

const finalMoney = computed(() => {
  if (selectedTrips.value.length > 0) {
    return selectedTrips.value
      .map(el => Number(el.pay_money))
      .reduce((acc, el) => acc + el)
  }
  else {
    return 0
  }
})

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<NormalTripData | IntercityTripData>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<NormalTripData | IntercityTripData>): Promise<LoadMoreData<NormalTripData | IntercityTripData>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  if (type.value === 'intercity') {
    const res = await fetchIntercityNotInvoicedOrderListAPI(
      { page: _page.toString(), limit: '10' },
      userInfoStore.userInfo!.token!,
    )
    return {
      list: res.data?.data.data || [],
      page: _page,
      total: res.data?.data.total || 9999,
    }
  }
  else {
    const res = await fetchNotInvoicedOrderListAPI(
      { page: _page.toString(), limit: '10' },
      userInfoStore.userInfo!.token!,
    )
    return {
      list: res.data?.data.data || [],
      page: _page,
      total: res.data?.data.total || 9999,
    }
  }
}

function handleSelect(trip: NormalTripData | IntercityTripData) {
  if (selectedTrips.value.includes(trip))
    selectedTrips.value = selectedTrips.value.filter(el => el !== trip)
  else
    selectedTrips.value.push(trip)
}

function handleNavToInvoiceForm() {
  router.push({
    name: 'invoiceForm',
    params: {
      type: type.value!,
      ids: selectedTrips.value.map(el => el.id.toString()).join(','),
      money: finalMoney.value.toString(),
    },
  })
}
</script>

<template>
  <!-- <view class="bg-#F3F3F3 p-24rpx text-28rpx text-#999999 leading-28rpx">
    2023年12月订单行程
  </view> -->
  <view v-if="dataList.length === 0" class="absolute left-1/2 top-1/2 text-28rpx text-#999999 -translate-1/2">
    暂无行程
  </view>
  <Trip
    v-for="item in dataList"
    :key="item.id"
    show-checkbox
    :is-selected="selectedTrips.includes(item)"
    :time="item.start_time"
    :type="type!"
    :order-type="item.type"
    :from="item.start_place"
    :to="item.end_place"
    :price="item.pay_money"
    @tap="handleSelect(item)"
  />
  <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  <!-- 底部栏 -->
  <view v-if="dataList.length > 0" class="fixed bottom-0 w-full bg-white x-center">
    <view class="px-24rpx py-30rpx text-32rpx font-medium leading-32rpx">
      <text class="text-#FA662F">
        {{ selectedTrips.length }}
      </text>
      个行程，共
      <text class="text-#FA662F">
        {{ finalMoney }}
      </text>
      元
    </view>
    <Divider width="750" />
    <view class="flex items-center justify-between px-24rpx py-30rpx">
      <view class="flex items-center" @tap="selectedTrips = dataList">
        <Checkbox :checked="selectedTrips.length === dataList.length" />
        <Spacer width="20" />
        <view class="text-32rpx text-#666666 font-medium leading-32rpx">
          全选
        </view>
      </view>
      <RGButton :disabled="selectedTrips.length > 0" size="small" corner="full" @tap="handleNavToInvoiceForm">
        下一步
      </RGButton>
    </view>
  </view>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'chooseTrip'
style:
  navigationBarTitleText: '选择行程'
</route>
